package whf.framework.log.events;

import org.hibernate.event.PostDeleteEvent;
import org.hibernate.event.PostDeleteEventListener;
import org.hibernate.event.PostInsertEvent;
import org.hibernate.event.PostInsertEventListener;
import org.hibernate.event.PostUpdateEvent;
import org.hibernate.event.PostUpdateEventListener;

import whf.framework.entity.Entity;
import whf.framework.log.env.Environment;
import whf.framework.log.util.AuditUtils;
import whf.framework.log.util.LogConfig;
import whf.framework.lucene.IndexConfig;
import whf.framework.lucene.IndexUtils;

/**
 * @author king
 * @create 2008-1-24 下午04:08:16
 * 
 */
@SuppressWarnings("serial")
public class HibernatePostEventListener implements PostDeleteEventListener, PostInsertEventListener, PostUpdateEventListener {

	/* (non-Javadoc)
	 * @see org.hibernate.event.PostDeleteEventListener#onPostDelete(org.hibernate.event.PostDeleteEvent)
	 */
	public void onPostDelete(PostDeleteEvent event) {
		Entity entity = (Entity)event.getEntity();
		if(IndexConfig.getIndexMode() == IndexConfig.IndexMode.AUTO) {
			IndexUtils.getInstance().removeIndex(entity);
		}
	}

	/* (non-Javadoc)
	 * @see org.hibernate.event.PostInsertEventListener#onPostInsert(org.hibernate.event.PostInsertEvent)
	 */
	public void onPostInsert(PostInsertEvent event) {
		Entity entity = (Entity)event.getEntity();
		if(LogConfig.isHistoriable(entity.getClass())) {
			AuditUtils.getInstance().logCreate(null, entity);
		}
		if(IndexConfig.getIndexMode() == IndexConfig.IndexMode.AUTO) {
			IndexUtils.getInstance().createIndex(entity);
		}
	}

	/* (non-Javadoc)
	 * @see org.hibernate.event.PostUpdateEventListener#onPostUpdate(org.hibernate.event.PostUpdateEvent)
	 */
	public void onPostUpdate(PostUpdateEvent event) {
		Entity entity = (Entity)event.getEntity();
		if(IndexConfig.getIndexMode() == IndexConfig.IndexMode.AUTO) {
			IndexUtils.getInstance().updateIndex(entity);
		}
		//
		if(LogConfig.isHistoriable(entity.getClass()) && !Environment.isLogIgnoredEntity(entity)) {
			Entity oldValue = Environment.get(entity);
			AuditUtils.getInstance().logUpdate(null, entity, oldValue);
		}
	}

}
